<template>
  <div id="issuedBox">
    <template v-if="isAccessUser">
      <div class="search-condition">
        <span>状态：</span>
        <el-select class="selector1"
                   v-model="status"
                   placeholder="请选择"
                   @change="handleChangeStatus">
          <el-option
            v-for="item in statusOptions"
            :key="item.enumStr"
            :label="item.name"
            :value="item.enumStr">
          </el-option>
        </el-select>
        <template v-if="!isFGLY">
          <span>类型：</span>
          <el-select v-model="type"
                     placeholder="请选择"
                     @change="handleChangeDisparageType">
            <el-option label="贬损下发" :value="0"></el-option>
            <el-option label="贬损转化" :value="1"></el-option>
            <el-option label="二次回访" :value="2"></el-option>
          </el-select>
        </template>

        <div class="advanced-search">
          <el-button type="text" @click="seniorFilter = !seniorFilter">{{seniorFilter?'收起':'更多'}}筛选条件</el-button>
          <div v-show="seniorFilter">
            <a-filter ref="filter" :conditions="conditions" @topLevelChange="getConditions"></a-filter>
            <el-row style="margin-top:-10px;text-align:center;">
              <el-button type="primary" @click="clickSeniorSearchBtn">搜索</el-button>
              <el-button type="info" plain @click="handleClearFilter">清空</el-button>
            </el-row>
          </div>
        </div>
      </div>
      <div class="report-btns" v-if="accessReport">
        <el-row>
          <el-col :span="24">
            <div class="btns">
              <a :href="exportReportUrl" download>
                <el-button type="primary">数据导出</el-button>
              </a>
              <router-link :to="{name: 'NpsReportsList'}">
                <el-button type="primary">报表</el-button>
              </router-link>
            </div>
          </el-col>
        </el-row>
      </div>
      <div class="search-list">

        <el-button
          type="primary"
          size="small"
          class="fast-next"
          v-if="isFGLY"
          :disabled="fastNextLoading"
          :loading="fastNextLoading"
          @click="handlFastNext">
          一键下发
        </el-button>

        <el-table
          v-loading="tbLoading"
          border
          element-loading-text="拼命加载中"
          :data="tableData"
          size=""
          @selection-change="handleSelectionChange"
          tooltip-effect="dark"
          style="width: 100%">

          <el-table-column type="selection" v-if="isFGLY" width="50"></el-table-column>

          <template v-for="item in tableHeads">
            <el-table-column
              v-if="item.fieldName !== 'derogatoryReason'"
              :width="getColumnWidth(item.fieldName)"
              :align="getColumnAlign(item.fieldName)"
              :formatter="getTextByCode"
              :prop="item.fieldName"
              :label="item.name"
              :key="item.fieldName">
            </el-table-column>
            <el-table-column v-else label="贬损原因" align="left" width="300">
              <template slot-scope="scope">
                <div v-html="getReason(scope.row)" style="text-align: left;"></div>
              </template>
            </el-table-column>
          </template>

          <!--<el-table-column-->
            <!--v-for="item in tableHeads"-->
            <!--:width="getColumnWidth(item.fieldName)"-->
            <!--:align="getColumnAlign(item.fieldName)"-->
            <!--:formatter="getTextByCode"-->
            <!--:prop="item.fieldName"-->
            <!--:label="item.name"-->
            <!--:key="item.fieldName">-->
          <!--</el-table-column>-->

          <el-table-column label="操作">
            <template slot-scope="scope">
              <template v-if="isFGLY">
                <el-button type="text" @click="toDetailsView(scope.row)">{{getManagerOpnBtnText(scope.row)}}
                </el-button>
              </template>
              <template v-else>
                <el-button type="text" @click="toDetailsView(scope.row)">详情</el-button>
                <el-button type="text" v-if="isAwaitApprove(scope.row)" @click="handleApprove(scope.row)">审批</el-button>
              </template>
            </template>
          </el-table-column>

        </el-table>
      </div>
      <div class="pagination">
        <el-pagination
          :current-page.sync="pagination.pageIndex"
          :page-size.sync="pagination.pageSize"
          layout="total, prev, pager, next, sizes, jumper"
          :total="tablePage.total"
          :page-sizes="[10, 20, 30, 50, 100]"
          @current-change="handlePagingCurrentChange"
          @size-change="handlePagingSizeChange">
        </el-pagination>
      </div>
      <approval-dialog ref="apDialog"
                       :baseInfo="apDialogBaseInfo"
                       :show.sync="dialogVisible"
                       @update="handlerUpdateTableData">
      </approval-dialog>
    </template>
    <div v-else class="reject-user">
      <div class="tips">
        <p>您没有操作权限！</p>
      </div>
    </div>
  </div>
</template>
<script>
  import env from '@/config/env'
  import {mapState, mapGetters} from 'vuex'
  import aFilter from '@/components/common/marketing/advancedFilter'
  import approvalDialog from './approvalDialog'
  import {
    getTopLevelPid,
    getFilterConditions,
    getFilterList,
    subAdminOneKeyNext
  } from '@/service/getData'


  export default {
    components: {aFilter, approvalDialog},
    data() {
      return {
        status: '0',
        type: 0,
        tbLoading: false,
        seniorFilter: false,
        statusOptions: [],
        filterList: {
          list: [],
          page: {}
        },
        conditions: {
          topLevel: [],
          subLevel: []
        },
        pagination: {
          pageIndex: 1,
          pageSize: 10,
          total: 0
        },
        dialogVisible: false,
        selectedRows: [],
        apDialogBaseInfo: {},
        fastNextLoading: false
      }
    },
    computed: {
      ...mapState({
        userInfo: state => state.userInfo,
        platformType: state => state.disparageManage.platformType,
        ctype: state => state.disparageManage.ctype
      }),
      ...mapGetters([
        'userType',
        'disparageType'
      ]),
      // 分公司管理员
      isFGLY() {
        return this.userType === this.platformType.FGLY
      },
      // 销司总部
      isXSZB() {
        return this.userType === this.platformType.XSZB
      },
      // 运营中心
      isYYZX() {
        return this.userType === this.platformType.YYZX
      },
      // 可接受的用户
      isAccessUser() {
        return this.isYYZX || this.isXSZB || this.isFGLY
      },
      // 报表权限
      accessReport() {
        return this.isYYZX
      },
      // 表标题
      tableHeads() {
        return this.conditions.topLevel
      },
      // 表数据
      tableData() {
        return this.filterList.list
      },
      // 表分页
      tablePage() {
        return this.filterList.page
      },
      // 状态搜索条件
      statusCondition() {
        const fields = ['derogatoryIssueStatus', 'derogatoryTransStatus', 'twCallbackStatus', 'brManagerStatus']
        const statusFieldName = fields[this.disparageType]
        return {
          content: this.status,
          fieldName: '',
          name: statusFieldName
        }
      },
      // 导出报表链接
      exportReportUrl() {
        const baseUrl = env.baseUrl3
        return baseUrl + `/nps/nps/export/deprator/data?UBToken=${localStorage.getItem('UBToken')}`
      }
    },
    created() {
      this.init()
    },
    methods: {

      init() {
        if (!this.isAccessUser) {
          return
        }
        this.type = this.disparageType
        this.handlerUpdateTableHeads()
        this.handlerUpdateTableData()
      },

      // 获取搜索条件和状态
      async getConditions(pid) {
        const user = this.userType
        const type = this.disparageType
        if (!pid) {
          const response = await getTopLevelPid({
            characterId: user,
            ctype: type,
            pid: null
          })
          pid = response.data.data.id
        }
        const res = await getFilterConditions({
          characterId: user,
          ctype: type,
          pid: pid
        })
        const conditions = res.data.data
        if (conditions[0].type == 1) {
          this.conditions.topLevel = conditions
          const oStatus = conditions.filter(item => item.name === '状态')[0]
          if (oStatus) {
            const statusRes = await getFilterConditions({
              characterId: user,
              ctype: type,
              pid: oStatus.id
            })
            let options = statusRes.data.data
            if (type == 2) {
              options = options.filter(item => {
                const exclude = ['6', '7', '14']
                return exclude.indexOf(item.enumStr) < 0
              })
            }
            this.statusOptions = options
          }
        } else if (conditions[0].type == 2) {
          this.conditions.subLevel = conditions
        }
      },

      // 筛选结果集
      async getFilterList(rules) {
        const currentIndex = this.pagination.pageIndex
        const pageSize = this.pagination.pageSize
        const conditions = Object.assign({
          characterId: this.userType,
          ctype: this.disparageType,
        }, rules)
        const res = await getFilterList(conditions, currentIndex, pageSize)
        this.filterList = res.data.data
        return res
      },

      // 设置表列宽
      getColumnWidth(column) {
        switch (column) {
          case 'salesSectionRecommendationScoreReasonsComment':
            return 300
          default:
            return ''
        }
      },

      // 设置对齐方式
      getColumnAlign(column) {
        switch (column) {
          case 'salesSectionRecommendationScoreReasonsComment':
            return 'left'
          default:
            return 'center'
        }
      },

      getReason(data) {
        let reasons = data.derogatoryReason
        const isMessage = /^\[/.test(reasons)
        if(isMessage) {
          try {
            reasons = data.derogatoryReason.replace(/;$/, '')
            reasons = JSON.parse(reasons)
            return reasons.map((reason, i) => {
              const key = reason.category
              const val = reason.content.join('，') || '无'
              return `(${i + 1}) ${key}：${val}`
            }).join('。<br/>')
          }catch (e) {
            return reasons
          }
        }
        return reasons
      },

      // 将状态码转为对应的中文
      getTextByCode(row, column, cellValue, rowIndex) {
        const map = {
          derogatoryCategories: ['其他', '卖场', '安装', '送货', '品牌', '服务', '产品'],
          derogatoryIssueStatus: ['全部', '待审', '已下发', '已驳回', '结束', '休眠'],
          derogatoryTransStatus: ['全部', '待审', '已通过', '已驳回', '已下发', '结束'],
          brManagerStatus: ['全部', '待下发', '待处理', '已处理', '已完成', '已求助', '已申诉', '结束'],
          twCallbackStatus: ['全部', '待审', '已下发', '已驳回', '完成', '休眠', '销代申述', '销代完成', '已求助', '已申诉', '已完成', '待处理', '已处理', '待下发', '分公司求助'],
          twCallbackViewStatus: ['全部', '待审', '已下发', '已驳回', '完成', '休眠', '待审', '待审', '已求助', '已申诉', '已完成', '待处理', '已处理', '待下发', '待审'],
          orTouch: ['否', '是'],
          orSatisfy: ['没处理', '还可以', '还行']
        }
        const fieldName = column.property === 'twCallbackStatus' ? 'twCallbackViewStatus' : column.property
        const statusCode = row[fieldName]
        if (!statusCode) {
          return cellValue
        }
        const statusItems = map[fieldName]
        return statusItems ? statusItems[+statusCode] : cellValue
      },

      // 更新表头和状态
      handlerUpdateTableHeads() {
        this.getConditions()
      },

      // 更新列表数据
      handlerUpdateTableData(rules = {}) {
        const conditions = Object.assign({
          relationType: 2,
          conditions: [this.statusCondition]
        }, rules)
        this.getFilterList(conditions)
      },

      // 点击搜索按钮
      clickSeniorSearchBtn() {
        this.pagination.pageIndex = 1
        this.handleSeniorFilter()
      },

      // 高级搜索
      handleSeniorFilter() {
        const rules = this.$_.cloneDeep(this.$refs.filter.rules)
        const filterConditions = rules.conditions.filter(item => {
          delete item.conType
          return !!item.name
        })
        const conditions = {
          relationType: rules.relationType || 2,
          conditions: [this.statusCondition].concat(filterConditions)
        }
        this.handlerUpdateTableData(conditions)
      },

      // 清空搜索条件
      handleClearFilter() {
        this.$refs.filter.clearCondition()
      },

      // 当前页码改变
      handlePagingCurrentChange(value) {
        this.pagination.pageIndex = value
        this.handleSeniorFilter()
      },

      // 页面容量改变
      handlePagingSizeChange(value) {
        this.pagination.pageSize = value
        this.pagination.pageIndex = 1
        this.handleSeniorFilter()
      },

      // 切换状态
      handleChangeStatus(value) {
        const fields = ['derogatoryIssueStatus', 'derogatoryTransStatus', 'twCallbackStatus', 'brManagerStatus']
        const status = this.statusOptions.filter(item => item.enumStr == value)[0]
        const fieldName = fields[status.ctype]
        const rules = {
          relationType: 2,
          conditions: [{
            content: value,
            fieldName: '',
            name: fieldName
          }]
        }
        this.pagination.pageIndex = 1
        this.handlerUpdateTableData(rules)
      },

      // 切换贬损类型
      handleChangeDisparageType(value) {
        this.status = '0'
        this.pagination.pageIndex = 1
        this.$store.commit('SET_DEROTYPE', value)
        this.handlerUpdateTableHeads()
        this.handlerUpdateTableData()
      },

      // 点击审批按钮
      handleApprove(row) {
        if (this.disparageType === this.ctype.BSZH) {
          this.toDetailsView(row)
        } else {
          const fields = ['derogatoryIssueStatus', 'derogatoryTransStatus', 'twCallbackStatus', 'brManagerStatus']
          const status = row[fields[this.disparageType]]
          this.apDialogBaseInfo = this.tableData.filter(item => item.orderid === row.orderid)[0]
          this.dialogVisible = true
          this.$store.commit('SET_CURRENTORDERUSERTYPE', row.characterId)
          this.$store.commit('SET_CURRENTORDERCTYPE', row.ctype)
          this.$store.commit('SET_CURRENTORDERSTATUS', status)
          this.$nextTick(() => {
            this.$store.commit('SET_CURRENTORDERDETAILS', row)
            this.$refs.apDialog.resetForm()
          })
        }
      },

      // 跳转详情页
      toDetailsView(row) {
        const fields = ['derogatoryIssueStatus', 'derogatoryTransStatus', 'twCallbackStatus', 'brManagerStatus']
        const status = row[fields[this.disparageType]]
        this.$router.push({
          name: 'DisparageDetails',
          params: {
            orderid: row.orderid
          },
          query: {
            ctype: row.ctype,
            status: status
          }
        })
      },

      // 是否显示审批按钮
      isAwaitApprove(row) {
        // 贬损下发、贬损转化、二次回访状态fieldName
        const fields = ['derogatoryIssueStatus', 'derogatoryTransStatus', 'twCallbackStatus']
        const fieldName = fields[this.disparageType]
        const status = row[fieldName]
        const approveStatus = ['1', '6', '7', '14']
        switch (fieldName) {
          case 'twCallbackStatus':
            return approveStatus.indexOf(status) > -1
          default:
            return status === '1'
        }
      },

      // 管理员操作按钮文本
      getManagerOpnBtnText(row) {
        const status = row.brManagerStatus
        if (status == 1) {
          return '下发'
        }
        if (status == 2) {
          return '处理'
        }
        return '查看'
      },

      // 分公司管理员列表选择
      handleSelectionChange(value) {
        this.selectedRows = value
      },

      // 把对象转成查询字符串
      jsonToQueryStr(data) {
        let result = []
        for (let key in data) {
          if (data.hasOwnProperty(key)) {
            result.push(`${key}=${data[key]}`)
          }
        }
        return result.join('&')
      },

      // 一键下发
      handlFastNext() {
        if (!this.selectedRows.length) {
          this.$message.warning('请选择下发订单！')
          return false
        }
        const orders = this.selectedRows.filter(item => item.brManagerStatus == 1).map(item => {
          return {
            orderid: item.orderid,
            characterId: item.characterId,
            ctype: item.ctype,
            processId: item.processId,
            taskId: item.taskId
          }
        })
        if (!orders.length) {
          this.$message.warning('未选择待下发订单！')
          return false
        }
        this.fastNextLoading = true
        subAdminOneKeyNext(orders).then(res => {
          const data = res.data
          if (data.code == 1) {
            this.$message.success(data.msgZ)
            this.handlerUpdateTableData()
          } else {
            this.$message.error('下发失败！')
          }
          this.fastNextLoading = false
        }).catch(err => {
          this.$message.error('下发失败！')
          this.fastNextLoading = false
        })
      },

    }
  }
</script>
<style lang="scss">

  .usertype {
    margin: 30px 0;
  }

  .selector1 {
    margin-right: 20px;
  }

  .fast-next {
    float: right;
    margin-bottom: 15px;
    /*border-color: #ff0000;*/
    /*background-color: #ff0000;*/
  }

  .reject-user {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: #f7f8fb;
    .tips {
      position: absolute;
      top: 50%;
      left: 50%;
      font-size: 14px;
      color: #999;
      text-align: center;
      transform: translate(-50%, -50%);
    }
  }

  #issuedBox {
    .search-condition {
      margin-bottom: 30px;
      .search-input {
        width: 400px;
      }
    }
    .search-list {

    }
    .advanced-search {
      margin-top: 10px;
    }
    .mrl10 {
      margin-left: 10px;
    }
  }

  .body_right .el-table th, .el-table--enable-row-transition .el-table__body td {
    text-align: center;
  }

  .report-btns {
    .btns {
      float: right;
      margin-bottom: 10px;
    }
  }

</style>
